var username;
var websocket;
const chatTemplate =
    "<li class='{0}'>" +
    "<img class='{3}' src='https://i.loli.net/2021/05/15/ahUncEmOrlwFCpM.png' width='60' height='60' alt=''>" +
    "    <div class='entete'>" +
    "        <h2>{1}</h2>" +
    "    </div>" +
    "    <div class='message'>" +
    "        {2}" +
    "    </div>" +
    "</li>";

const onlineTemplate =
    "            <li>" +
    "                <img src='https://i.loli.net/2021/05/15/ahUncEmOrlwFCpM.png' width='64' height='64' alt=''>" +
    "                <div>" +
    "                    <h2>{0}</h2>" +
    "                    <h3>" +
    "                        <span class='status green'></span>" +
    "                        在线" +
    "                    </h3>" +
    "                </div>" +
    "            </li>";

const tipsTemplate =
    "<li class='tips'>{0}</li>";


String.format = function() {
    if (arguments.length == 0)
        return null;
    var str = arguments[0];
    for ( var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
};

$("#sendButton").click(function (){
    sendText();
});

$("#messageInput").keypress(function (e){
    if(e.keyCode === 13){
        sendText();
        e.preventDefault();
    }
});

//判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址
if ('WebSocket' in window) {
    websocket = new WebSocket("ws://" +  window.location.host + "/connect");
}

//接收到消息的回调方法
websocket.onmessage = function(event) {
    console.log(event.data);
    receiveMessage(JSON.parse(event.data));
}

websocket.onclose = function(event) {
    location.reload();
}

//将消息显示在网页上
function receiveMessage(json) {
    console.log(json)
    if(json.tag === "USERNAME"){
        username = json.message;
    }
    if(username == null) return;
    if(json.tag === "TEXT"){
        var how = "me";
        var head = "head-left";
        if(json.username !== username){
            how = "you";
            head = "head-right";
        }
        const jqChat = $("#chat");
        jqChat.html(jqChat.html() + String.format(chatTemplate,how,json.username,json.message,head));
    }
    if(json.tag === "ONLINELIST"){
        const onlineListDiv = $("#onlineList");
        const onlineListJson = JSON.parse(json.message);
        const onlineList = onlineListJson.onlineList;
        onlineListDiv.html("");
        for (let i = 0; i < onlineList.length; i++) {
            onlineListDiv.html(onlineListDiv.html() + String.format(onlineTemplate,onlineList[i].username));
        }
    }
    if(json.tag === "TIPS"){
        const jqChat = $("#chat");
        jqChat.html(jqChat.html() + String.format(tipsTemplate,json.message));
    }
    if(json.tag === "IMAGE"){
        var how = "me";
        var head = "head-left";
        if(json.username !== username){
            how = "you";
            head = "head-right";
        }
        const jqChat = $("#chat");
        jqChat.html(jqChat.html() + String.format(chatTemplate,how,json.username,json.message,head));
    }
    const jsChat = document.getElementById("chat");
    jsChat.scrollTop = jsChat.scrollHeight;
}


//发送消息
function sendText() {
    const message = $("#messageInput").val();
    if(message === "") return;
    $("#messageInput").val("");
    websocket.send(JSON.stringify({
        tag: "TEXT",
        username: username,
        message: message
    }));

}

//发送图片
function sendImage(imageName) {
    $("#imagefile").val("");
    websocket.send(JSON.stringify({
        tag: "IMAGE",
        username: username,
        message: "<img height='250' src='//" + window.location.host + "/uploadimages/" +imageName + "'/>"
    }));

}


$("#imagebuttom").click(function(){
    $("#imagefile").click();
});
$("#imagefile").change(function(){
    var f=this.files[0];
    var formData=new FormData();
    formData.append('file',f);
    $.ajax({
        url: "//" + window.location.host +"/upload",
        type: 'POST',
        success: function(data){
            console.log(data);
            const json = JSON.parse(data);
            if(!json.success){
                alert(json.message);
                return;
            }
            sendImage(json.message);
        },
        data:formData,
        cache: false,
        contentType: false,
        processData: false
    });
});